<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">

<head>
    <title>未读消息</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js" type="text/javascript"></script>
    <script src="/vue.min.js" type="text/javascript"></script>
    <script src="/js/index.js"></script>
    <link rel="stylesheet" href="/style.css" type="text/css" />
    <link rel="stylesheet" href="/push.css" type="text/css" />

    <script>
        let source = null;

        // 用时间戳模拟登录用户
        const userId = new Date().getTime();

        if (window.EventSource) {

            // 建立连接
            source = new EventSource('http://localhost:7777/sse/sub/7777');
            setMessageInnerHTML("连接用户=" + userId);
            /**
             * 连接一旦建立，就会触发open事件
             * 另一种写法：source.onopen = function (event) {}
             */
            source.addEventListener('open', function (e) {
                setMessageInnerHTML("建立连接。。。");
            }, false);

            /**
             * 客户端收到服务器发来的数据
             * 另一种写法：source.onmessage = function (event) {}
             */
            source.addEventListener('message', function (e) {
                setMessageInnerHTML(e.data);
            });


            /**
             * 如果发生通信错误（比如连接中断），就会触发error事件
             * 或者：
             * 另一种写法：source.onerror = function (event) {}
             */
            source.addEventListener('error', function (e) {
                if (e.readyState === EventSource.CLOSED) {
                    setMessageInnerHTML("连接关闭");
                } else {
                    console.log(e);
                }
            }, false);

        } else {
            setMessageInnerHTML("你的浏览器不支持SSE");
        }

        // 监听窗口关闭事件，主动去关闭sse连接，如果服务端设置永不过期，浏览器关闭后手动清理服务端数据
        window.onbeforeunload = function () {
            closeSse();
        };

        // 关闭Sse连接
        function closeSse() {
            source.close();
            const httpRequest = new XMLHttpRequest();
            httpRequest.open('GET', 'http://localhost:7788/sse/close/' + userId, true);
            httpRequest.send();
            console.log("close");
        }

        // 将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            $("#arrivedDiv").append("<br/>"+innerHTML);
            var count = $("#count").text();
            count = Number(count) + 1;
            $("#count").text(count);
        }


        function sendMessage() {
            var content = $("#message").val();
            $.ajax({
                url: '/sse/push',
                type: 'GET',
                data: { "id": "7777", "content": content },
                success: function (data) {

                    console.log(data)
                },
                error: function (err) {

                },
                done: function () {

                }
            })
        }


    </script>
</head>


<body>
    <div>
        <ul>
            <li class="active"><i class="fa fa-home fa-lg"></i> 未读消息 <span id="count" class="unread">0</span></li>

        </ul>
        <div style="margin-left: 800px;">
            <input style="height: 25px; width: 180px;" maxlength="60" value="" id="message" />
            <button class="button" id="mySendBtn" onclick="sendMessage()"> 点击发送</button>
            <div style="font-size: 20px;color: darkcyan"> 接收到的mqtt消息</div>
            <hr />
            <div id="arrivedDiv" style="height:200px; width:300px; overflow:scroll; background:#EEEEEE;">
                <br />
            </div>
        </div>
    </div>
</body>

</html>